"""
Data Parser

实现雷达数据类型转换和解析
"""

import struct
from dataclasses import dataclass
from typing import List, Dict, Any
from ..exceptions import RadarDataFormatError


@dataclass
class RadarTarget:
    """雷达目标数据结构"""
    target_id: int      # 目标ID
    range_val: float    # 距离(m)
    azimuth: float      # 方位角(deg)
    elevation: float    # 俯仰角(deg)
    velocity: float     # 速度(m/s)
    rcs: float         # RCS值(dBsm)
    quality: int       # 信号质量(0-100)
    track_type: int    # 跟踪类型

    @classmethod
    def from_bytes(cls, data: bytes) -> 'RadarTarget':
        """从字节数组解析雷达目标数据"""
        try:
            # 使用大端序解析数据
            target_id = struct.unpack('>I', data[0:4])[0]
            range_val = struct.unpack('>f', data[4:8])[0]
            azimuth = struct.unpack('>f', data[8:12])[0]
            elevation = struct.unpack('>f', data[12:16])[0]
            velocity = struct.unpack('>f', data[16:20])[0]
            rcs = struct.unpack('>f', data[20:24])[0]
            quality = struct.unpack('>H', data[24:26])[0]
            track_type = data[26]

            return cls(
                target_id=target_id,
                range_val=range_val,
                azimuth=azimuth,
                elevation=elevation,
                velocity=velocity,
                rcs=rcs,
                quality=quality,
                track_type=track_type
            )
        except struct.error as e:
            raise RadarDataFormatError(f"解析雷达目标数据失败: {e}")

    def to_bytes(self) -> bytes:
        """将雷达目标数据转换为字节数组"""
        try:
            data = bytearray()
            data.extend(struct.pack('>I', self.target_id))
            data.extend(struct.pack('>f', self.range_val))
            data.extend(struct.pack('>f', self.azimuth))
            data.extend(struct.pack('>f', self.elevation))
            data.extend(struct.pack('>f', self.velocity))
            data.extend(struct.pack('>f', self.rcs))
            data.extend(struct.pack('>H', self.quality))
            data.extend(struct.pack('>B', self.track_type))
            return bytes(data)
        except struct.error as e:
            raise RadarDataFormatError(f"转换雷达目标数据失败: {e}")

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'target_id': self.target_id,
            'range': self.range_val,
            'azimuth': self.azimuth,
            'elevation': self.elevation,
            'velocity': self.velocity,
            'rcs': self.rcs,
            'quality': self.quality,
            'track_type': self.track_type
        }


@dataclass
class RadarStatus:
    """雷达状态数据结构"""
    radar_status: int    # 雷达状态
    temperature: float  # 温度(°C)
    voltage: float      # 电压(V)
    uptime: int         # 运行时间(s)
    error_code: int     # 错误代码

    @classmethod
    def from_bytes(cls, data: bytes) -> 'RadarStatus':
        """从字节数组解析雷达状态数据"""
        try:
            radar_status = data[0]
            temperature = struct.unpack('>f', data[1:5])[0]
            voltage = struct.unpack('>f', data[5:9])[0]
            uptime = struct.unpack('>I', data[9:13])[0]
            error_code = struct.unpack('>H', data[13:15])[0]

            return cls(
                radar_status=radar_status,
                temperature=temperature,
                voltage=voltage,
                uptime=uptime,
                error_code=error_code
            )
        except struct.error as e:
            raise RadarDataFormatError(f"解析雷达状态数据失败: {e}")

    def to_bytes(self) -> bytes:
        """将雷达状态数据转换为字节数组"""
        try:
            data = bytearray()
            data.extend(struct.pack('>B', self.radar_status))
            data.extend(struct.pack('>f', self.temperature))
            data.extend(struct.pack('>f', self.voltage))
            data.extend(struct.pack('>I', self.uptime))
            data.extend(struct.pack('>H', self.error_code))
            return bytes(data)
        except struct.error as e:
            raise RadarDataFormatError(f"转换雷达状态数据失败: {e}")

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'radar_status': self.radar_status,
            'temperature': self.temperature,
            'voltage': self.voltage,
            'uptime': self.uptime,
            'error_code': self.error_code
        }


class DataParser:
    """数据解析器"""

    @staticmethod
    def parse_targets(data: bytes) -> List[RadarTarget]:
        """解析多个雷达目标数据"""
        targets = []
        target_size = 27  # 每个目标数据27字节

        if len(data) % target_size != 0:
            raise RadarDataFormatError(f"目标数据长度不正确: {len(data)}")

        for i in range(0, len(data), target_size):
            target_data = data[i:i + target_size]
            targets.append(RadarTarget.from_bytes(target_data))

        return targets

    @staticmethod
    def pack_targets(targets: List[RadarTarget]) -> bytes:
        """打包多个雷达目标数据"""
        data = bytearray()
        for target in targets:
            data.extend(target.to_bytes())
        return bytes(data)